
// Helper functions to enable a useful pattern of using scoped pointers in
// which the ownership of the memory is transferred out to an empty
// scoped_ptr or scoped_array.
//
// The usage pattern is as follows:
//    void foo(Bar** b);
//
//    scoped_ptr<B> p;
//    foo(address(p));
//
// To receive the ownership of the resource the scoped pointer must be
// empty, otherwise it will leak.
//
// As an implementation detail, the scoped pointers in "base/scoped_ptr.h" do
// not offer support for this idiom. The code below may break if the
// implementation of the scoped_ptr changes. The code works with the vast
// majority of the scoped_ptr implementations though.


#ifndef LONGKEY_COMMON_SCOPED_PTR_ADDRESS_H_
#define LONGKEY_COMMON_SCOPED_PTR_ADDRESS_H_

#include "basictypes.h"
#include "scoped_ptr.h"
#include "debug.h"

template <typename T>
inline T** address(const scoped_ptr<T>& t)
{
	COMPILE_ASSERT(sizeof(T*) == sizeof(scoped_ptr<T>), types_do_not_match);
	ASSERT1(!t.get());
	return reinterpret_cast<T**>(&const_cast<scoped_ptr<T>&>(t));
}

template <typename T>
inline T** address(const scoped_array<T>& t)
{
	COMPILE_ASSERT(sizeof(T*) == sizeof(scoped_ptr<T>), types_do_not_match);
	ASSERT1(!t.get());
	return reinterpret_cast<T**>(&const_cast<scoped_array<T>&>(t));
}

#endif	// LONGKEY_COMMON_SCOPED_PTR_ADDRESS_H_